package com.zlsy.thread.objectandthreadcommonsuse;

/**
 * @author zhouliang
 * @date 2020/03/04
 * @desc wait和notify的基本使用方法
 **/
public class WaitUse {



    static final Object object = new Object();

    /**
     * 另外一个线程调用这个对象的notify方法唤醒当前释放锁的线程
     */
    private static class Thread1 extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                System.out.println(Thread.currentThread().getName() + "开始执行了");
                try {
                    //线程释放锁 注意：在释放锁之后该线程就进入等待被唤醒的状态，thread2调用了同一个对象的唤醒，并不意味着
                    //thread1肯定会继续往下执行，前提是能获得这个锁。
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "我又再次获得锁了");
            }
        }
    }

    private static class Thread2 extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                //唤醒
                object.notify();
                System.out.println(Thread.currentThread().getName() + "调用了notify()方法");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
        thread1.start();
        Thread.sleep(300);
        thread2.start();
    }

}
